package br.pucrs.lognplay.faces.bean;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.entity.StaticView;
import br.pucrs.lognplay.entity.StaticView.Status;
import br.pucrs.lognplay.entity.User.Role;
import br.pucrs.lognplay.service.StaticViewManagementService;

@ManagedBean
@RequestScoped
public class StaticViewListBean extends Bean {

	private List<StaticView> staticViews;

	@EJB
	private StaticViewManagementService staticViewManagementService;

	public List<StaticView> getStaticViews() {
		try {
			if (staticViews == null) {
				Role loggedUserRole = getLoggedUser().getRole();

				if (loggedUserRole.equals(Role.MASTER_USER)) {
					staticViews = staticViewManagementService.listAllStaticViews();
				} else if (loggedUserRole.equals(Role.CLIENT_MASTER_USER)) {
					Client loggedUserClient = getLoggedUser().getClient();
					staticViews = staticViewManagementService.listStaticViewsByClientId(loggedUserClient.getId());
				}
			}

			return staticViews;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}

	public String removeStaticView() {
		try {
			String staticViewId = getParameterValue("staticViewId");

			for (StaticView staticView : staticViews) {
				if (staticView.getId().equals(staticViewId)) {
					staticView.setStatus(Status.PENDING_REMOVAL);
					staticViewManagementService.mergeStaticView(staticView);
				}
			}

			addInformationMessage("The Static View has been marked to be removed", null);
			return null;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}
}
